package com.psp.bu.netease;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;

import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import org.apache.log4j.Logger;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;

/**
 * 网易云信管理类
 * 
 * @author cuihaidong
 *
 */
public class NeteaseManager {
	private Logger logger = Logger.getLogger(NeteaseManager.class);
	static String appKey = "0122e119de19a63125fd1de683bc9503";
	static String appSecret = "f4300b0489af";

	/**
	 * 创建账户
	 */
	final String URL_Create = "https://api.netease.im/nimserver/user/create.action";
	/**
	 * 更新账户
	 */
	final String URL_Update = "https://api.netease.im/nimserver/user/update.action";
	/**
	 * 刷新token
	 */
	final String URL_RefreshToken = "https://api.netease.im/nimserver/user/refreshToken.action";

	/**
	 * 更新用户名片信息
	 */
	final String URL_User_UpdateUinfo = "https://api.netease.im/nimserver/user/updateUinfo.action";
	/**
	 * 获取用户名片信息
	 */
	final String URL_User_GetUinfo = "https://api.netease.im/nimserver/user/getUinfos.action";
	/**
	 * 发送消息
	 */
	final String URL_SendMsg = "https://api.netease.im/nimserver/msg/sendMsg.action";

	/**
	 * 添加好友
	 */
	final String URL_AddFriend = "https://api.netease.im/nimserver/friend/add.action";

	/**
	 * 构造器
	 * 
	 * @param appKey
	 * @param appSecret
	 */
	public NeteaseManager(String appKey, String appSecret) {
		this.appKey = appKey;
		this.appSecret = appSecret;
	}

	/**
	 * 创建网易云信账号
	 * 
	 * @param accid
	 * @param name
	 * @param props
	 * @param icon
	 * @param token
	 */
	public NeteaseAccount create(String accid, String name, String props, String icon, String token) {
		Map<String, String> params = new HashMap<>();
		params.put("accid", accid);
		params.put("name", name);
		if (props != null)
			params.put("props", props);
		if (icon != null)
			params.put("icon", icon);
		if (token != null)
			params.put("token", token);

		String res = post(URL_Create, params);
		if (res != null) {
			JSONObject json = JSON.parseObject(res);
			int code = json.getIntValue("code");
			if (code == 200) {
				NeteaseAccount account = JSON.parseObject(json.getString("info"), NeteaseAccount.class);
				return account;
			}
		}
		return null;
	}

	/**
	 * 更新网易云信账户
	 * 
	 * @param accid
	 * @param props
	 * @param token
	 */
	public void update(String accid, String props, String token) {
		Map<String, String> params = new HashMap<>();
		params.put("accid", accid);
		if (props != null)
			params.put("props", props);
		if (token != null)
			params.put("token", token);

		String json = post(URL_Update, params);
		if (json != null) {

		}
	}

	/**
	 * 刷新token
	 * 
	 * @param accid
	 */
	public NeteaseAccount refreshToken(String accid) {
		Map<String, String> params = new HashMap<>();
		params.put("accid", accid);

		String res = post(URL_RefreshToken, params);
		if (res != null) {
			JSONObject json = JSON.parseObject(res);
			int code = json.getIntValue("code");
			if (code == 200) {
				NeteaseAccount account = JSON.parseObject(json.getString("info"), NeteaseAccount.class);
				return account;
			}
		}
		return null;
	}

	/**
	 * 更新用户名片
	 * 
	 * @param accid
	 *            String 是 用户帐号，最大长度32字符，必须保证一个APP内唯一
	 * @param name
	 *            String 否 用户昵称，最大长度64字符
	 * @param icon
	 *            String 否 用户icon，最大长度1024字符
	 * @param sign
	 *            String 否 用户签名，最大长度256字符
	 * @param email
	 *            String 否 用户email，最大长度64字符
	 * @param birth
	 *            String 否 用户生日，最大长度16字符
	 * @param mobile
	 *            String 否 用户mobile，最大长度32字符，只支持国内号码
	 * @param gender
	 *            int 否 用户性别，0表示未知，1表示男，2女表示女，其它会报参数错误
	 * @param ex
	 *            String 否 用户名片扩展字段，最大长度1024字符，用户可自行扩展，建议封装成JSON字符串
	 */
	public void updateUinfo(String accid, String name, String icon, String sign, String email, String birth,
			String mobile, Integer gender, String ex) {
		Map<String, String> params = new HashMap<>();
		params.put("accid", accid);
		if (name != null) {
			params.put("name", name);
		}
		if (icon != null) {
			params.put("icon", icon);
		}
		if (sign != null) {
			params.put("sign", sign);
		}
		if (email != null) {
			params.put("email", email);
		}
		if (birth != null) {
			params.put("birth", birth);
		}
		if (mobile != null) {
			params.put("mobile", mobile);
		}
		if (gender != null) {
			params.put("gender", String.valueOf(gender));
		}
		if (ex != null) {
			params.put("ex", ex);
		}
		String json = post(URL_User_UpdateUinfo, params);
		if (json != null) {

		}
	}

	/**
	 * 获取用户信息
	 * 
	 * @param accids
	 */
	public void getUinfo(List<String> accids) {
		Map<String, String> params = new HashMap<>();
		params.put("accids", JSON.toJSONString(accids));

		String json = post(URL_User_GetUinfo, params);
		if (json != null) {

		}

	}

	/**
	 * 添加好友--两人保持好友关系
	 * 
	 * @param accid
	 *            加好友发起者accid
	 * @param faccid
	 *            加好友接收者accid
	 * @param type
	 *            1直接加好友，2请求加好友，3同意加好友，4拒绝加好友
	 * @param msg
	 *            加好友对应的请求消息，第三方组装，最长256字符
	 */
	public void addFriend(String accid, String faccid, Integer type, String msg) {
		Map<String, String> params = new HashMap<>();
		params.put("accid", accid);
		params.put("faccid", faccid);
		if (type != null) {
			params.put("type", String.valueOf(type));
		} else {
			params.put("type", "1");
		}
		if (msg != null) {
			params.put("msg", msg);
		}

		String res = post(URL_AddFriend, params);
		if (res != null) {
			JSONObject json = JSON.parseObject(res);
			int code = json.getIntValue("code");
			if (code == 200) {

			}
		}
	}

	/**
	 * post
	 * 
	 * @param url
	 * @param params
	 * @return
	 */
	private String post(String url, Map<String, String> params) {
		CloseableHttpClient httpClient = HttpClients.createDefault();
		HttpPost httpPost = new HttpPost(url);

		String nonce = UUID.randomUUID().toString().replace("-", "");
		String curTime = String.valueOf((new Date()).getTime() / 1000L);
		String checkSum = CheckSumBuilder.getCheckSum(appSecret, nonce, curTime);// 参考
																					// 计算CheckSum的java代码
		// 设置请求的header
		httpPost.addHeader("AppKey", appKey);
		httpPost.addHeader("Nonce", nonce);
		httpPost.addHeader("CurTime", curTime);
		httpPost.addHeader("CheckSum", checkSum);
		httpPost.addHeader("Content-Type", "application/x-www-form-urlencoded;charset=utf-8");

		// 设置请求的参数
		List<NameValuePair> nvps = new ArrayList<NameValuePair>();
		for (String key : params.keySet()) {
			String value = params.get(key);
			nvps.add(new BasicNameValuePair(key, value));
		}
		try {
			httpPost.setEntity(new UrlEncodedFormEntity(nvps, "utf-8"));
			// 执行请求
			HttpResponse response = httpClient.execute(httpPost);
			// 打印执行结果
			String json = EntityUtils.toString(response.getEntity(), "utf-8");
			logger.info("netease response data is :" + json);
			return json;
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		} catch (ClientProtocolException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
		return null;
	}
}
